<!--
 作者：ex_wangshuai
 日期：2016-11-15
 功能：针对 首页-掌天下-产品平台和店铺分布 的可锁定头及列的表格组件
 参数：需要传进来的参数：'tableTitle', 'thead', 'gridColumns', 'tableRows', 'height'
 事件：点击表头对当前列进行排序
-->
<template>
  <div>
    <div id="divBox1" :style="{'max-height':height}">
      <table id="tbTest1" style="text-align:center;background:rgba(244,249,255,0.4);">
        <tr>
          <th v-for="item in thead" @click="sortBy(item)">
            {{item}}<img style="width:0.16rem;height:0.20rem;margin-left:4px;" :src="filterUrl" alt="" v-if="$index!=0&&$index!=1&&$index!=2" data-img="{{filterUrl}}">
          </th>
        </tr>
        <tr v-for="row in tableRows  | orderBy sortBykey sortOrders[sortKey]">
          <td v-for="item in gridColumns" v-html="row[item] | numberFilter" :id="$parent.$index" :class="{'under-line': item == 'title'}" @click="routeStore(item, row['item_url'])">
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
  /*eslint-disable*/
  var hasLeft = '';
  var hasHead = '';

  function oFixedTable(id, obj, _cfg) {
    this.id = id;
    this.obj = obj;
    this.box = this.obj.parentNode;
    this.config = {
      fixHead: _cfg.fixHead || true,
      rows: _cfg.rows || 1,
      cols: _cfg.cols || 0,
      background: _cfg.background || '#ffffff',
      zindex: _cfg.zindex || 10
    };
    this._fixTable(this)
  }

  oFixedTable.prototype._fixTable = function(_) {
    if(_.obj.rows.length <= 0) {
      return false;
    }
    var hasLeft = _.buildLeft();
    var hasHead = _.buildHead();

    _.divLeft.onscroll = function () {
      _.box.scrollTop = this.scrollTop;
    }

    _.box.onscroll = function() {
      if(_.divHead != null) {
        _.divHead.scrollLeft = this.scrollLeft;
      }
      if(_.divLeft != null) {
        _.divLeft.scrollTop = this.scrollTop;
      }
    };
    if(hasHead && hasLeft) {
      _.buildTopLeft();
    }
  };

  oFixedTable.prototype.buildHead = function() {
    var _ = this;
    var strDivId = _.id + '_div_head';
    var strTbId = _.id + '_tb_header';
    var div = document.createElement('div');
    div.id = strDivId;
    div.style.cssText = 'position:absolute;overflow:hidden;z-index:' + (_.config.zindex + 1) + ';';
    div.innerHTML = '<table id="' + strTbId + '" cellpadding="0" cellspacing="0" style="background:' + _.config.background + ';"></table>';

    if (document.getElementById(strDivId)) {
      _.box.removeChild(document.getElementById(strDivId))
    }
    _.box.insertBefore(div, _.obj);

    _.divHead = div;
    _.tbHead = document.getElementById(strTbId);

    //判断是否出现纵向滚动条，若出现，高度减去滚动条宽度 16px
    var sw = _.obj.offsetHeight > _.box.offsetHeight ? 0 : 0;
    _.divHead.style.width = (_.box.offsetWidth - sw) + 'px';

    _.tbHead.style.textAlign = _.obj.style.textAlign;
    _.tbHead.style.width = _.obj.offsetWidth + 'px';

    var hasHead = false;
    if(_.config.fixHead && _.obj.tHead != null) {
      var tHead = _.obj.tHead;
      _.tbHead.appendChild(tHead.cloneNode(true));
      hasHead = true;
    } else {
      for(var i = 0; i < _.config.rows; i++) {
        var row = _.obj.rows[i];
        if(row != null) {
          _.tbHead.appendChild(row.cloneNode(true));
          hasHead = true;
        }
      }
    }
    return hasHead;
  };

  oFixedTable.prototype.buildLeft = function() {
    var _ = this;
    if(_.config.cols <= 0) {
      return false;
    }
    var strDivId = _.id + '_div_left';
    var strTbId = _.id + '_tb_left';
    var div = document.createElement('div');
    div.id = strDivId;
    div.style.cssText = 'position:absolute;overflow-x:hidden;overflow-y:scroll;z-index:' + _.config.zindex + ';box-sizing:border-box;border-right:1px solid #dddddd;width: 2rem;';
    div.innerHTML = '<table id="' + strTbId + '" cellpadding="0" cellspacing="0" style="background:' + _.config.background + ';"></table>';

    if (document.getElementById(strDivId)) {
      _.box.removeChild(document.getElementById(strDivId))
    }
    _.box.insertBefore(div, _.obj);

    _.divLeft = div;
    _.tbLeft = document.getElementById(strTbId);

    _.tbLeft.style.textAlign = _.obj.style.textAlign;

    //判断是否出现横向滚动条，若出现，高度减去滚动条高度 16px
    var sw = _.obj.offsetWidth > _.box.offsetWidth ? 0 : 0;
    _.divLeft.style.height = (_.box.offsetHeight - sw) + 'px';

    var hasLeft = false;
    for(var i = 0, rows = _.obj.rows.length; i < rows; i++) {
      var row = _.tbLeft.insertRow(_.tbLeft.rows.length);
      row.style.cssText = _.obj.rows[i].style.cssText;

      for(var j = 0; j < _.config.cols; j++) {
        var cell = _.obj.rows[i].cells[j];
        if(cell != null) {
          row.appendChild(cell.cloneNode(true));
          cell.style.cssText = _.obj.rows[i].cells[j].style.cssText;
          hasLeft = true;
        }
      }
    }
    return hasLeft;
  };

  oFixedTable.prototype.buildTopLeft = function() {
    var _ = this;
    var strDivId = _.id + '_div_top_left';
    var strTbId = _.id + '_tb_top_left';
    var div = document.createElement('div');
    div.id = strDivId;
    div.style.cssText = 'position:absolute;overflow:hidden;z-index:' + (_.config.zindex + 2) + ';width: 2rem;';
    div.innerHTML = '<table id="' + strTbId + '" cellpadding="0" cellspacing="0" style="background:' + _.config.background + ';"></table>';

    if (document.getElementById(strDivId)) {
      _.box.removeChild(document.getElementById(strDivId))
    }
    _.box.insertBefore(div, _.obj);

    var tbTopLeft = document.getElementById(strTbId);
    tbTopLeft.style.textAlign = _.obj.style.textAlign;

    for(var i = 0; i < _.config.rows; i++) {
      var row = tbTopLeft.insertRow(tbTopLeft.rows.length);
      row.style.cssText = _.obj.rows[i].style.cssText;

      for(var j = 0; j < _.config.cols; j++) {
        var cell = _.obj.rows[i].cells[j];
        if(cell != null) {
          row.appendChild(cell.cloneNode(true));
          cell.style.cssText = _.obj.rows[i].cells[j].style.cssText;
          hasLeft = true;
        }
      }
    }
  };


  export default{
    // 接收父组件传过来的参数
    props: ['tableRows', 'gridColumns', 'thead', 'store', 'height'],
    // 监控
    watch: {
      'tableRows': function (val) {
        var self = this
        setTimeout(function() {
          var ofix1 = new oFixedTable('ofix1', document.getElementById('tbTest1'), {
            rows: 1,
            cols: 1
          })
        }, 0)
        // 在表格数据为空时不再执行避免报错
        if (!val.length) {
          return
        }
        setTimeout(function () {
          var tbObj = document.getElementById('ofix1_tb_header')
          tbObj.addEventListener('click',function (event) {
            if(event.target.tagName === 'TH'){
              self.sortBy(event.target.innerText, event)
            }
          })
          // 筛选时表格头部同步滚动
          var tdDomHeader = document.querySelectorAll('#ofix1_div_head')
          var tdDomLeft = document.querySelectorAll('#ofix1_div_left')
          tdDomLeft[0].scrollTop = document.querySelectorAll('#divBox1')[0].scrollTop
          tdDomHeader[0].scrollLeft = document.querySelectorAll('#divBox1')[1].scrollLeft
        }, 1)
      }
    },
    data: function() {
      var sortOrders = {}
      this.gridColumns.forEach(function (key) {
        sortOrders[key] = 1
      })
      return {
        filterUrl: './static/img/indus/filter1.png',
        sortKey: 'sales_amount',
        sortOrders: sortOrders
      }
    },
    methods: {
      routeStore: function (value, store) {
        if (value === 'title') {
        	store = store.replace('detail.tmall', 'detail.m.tmall')
        	if (window.util.getDevInfo() === 1) {
            // IOS
            window.cordova.exec(function(success) {}, function(error) {
              alert('打开页面失败')
              console.log(error)
            }, 'MideaCommon', 'openUrl', [store])
          } else {
            // 安卓，走页面打开
            store = store.replace('?', '&')
            this.$route.router.go('/industry/tianmaoStore?url=' + encodeURIComponent(store))
          }
        }
      },
      sortBykey: function (a, b) {
        return parseFloat(b[this.sortKey]) - parseFloat(a[this.sortKey])
      },
      sortBy: function (key, event) {
        // 每一次排序之前所有的图片重置
        var imgDom = document.querySelectorAll('#ofix1_tb_header th img')
        for (var x = 0; x < imgDom.length; x++) {
          imgDom[x].setAttribute('src', './static/img/indus/filter1.png')
        }
        // 排序
        var activeTheadIndex = 0
        for (var i = 0; i < this.thead.length; i++) {
          if (this.thead[i] === key) {
            activeTheadIndex = i
          }
        }
        this.sortKey = this.gridColumns[activeTheadIndex]
        this.sortOrders[this.gridColumns[activeTheadIndex]] = this.sortOrders[this.gridColumns[activeTheadIndex]] * -1
        // 排序时同步改变标识图片
        if (this.sortOrders[this.gridColumns[activeTheadIndex]] > 0) {
          event.target.getElementsByTagName('img')[0].setAttribute('src', './static/img/indus/filter3.png')
        } else {
          event.target.getElementsByTagName('img')[0].setAttribute('src', './static/img/indus/filter2.png')
        }
        // 排序时同步改变左边第一列的内容
        setTimeout(function(){
          var tdDom = document.querySelectorAll('#tbTest1 tr td:nth-child(1)')
          var tdDomLeft = document.querySelectorAll('#ofix1_tb_left td')
          for (var y = 0; y < tdDom.length; y++) {
            tdDomLeft[y].innerHTML = tdDom[y].innerHTML
          }
        },0)
      }
    },
    filters: {
      numberFilter: function (value) {
        if (value == 0) {
          return '0'
        } else if (!value) {
          return '/'
        } else {
          return value
        }
      }
    },
    components: {
    },
    ready: function() {
      var sortOrders = {}
      this.gridColumns.forEach(function (key) {
        sortOrders[key] = 1
      })
      this.sortOrders = sortOrders
    }
  }
</script>
<style lang="scss" scoped>
  #divBox1{
    overflow:auto;
    width:100%;
    font-size: 0.28rem;
    color: #999;
  }
  table {
    table-layout : fixed;
  }

  table td,
  table th {
    width: 2rem;
    height: 1rem;
    padding: 0;
    color: #999999;
    vertical-align: middle;
    /*box-sizing: border-box;*/
  }

  table th{
    background: rgba(188,219,255,0.4);
    font-weight: normal;
    /*padding-top:2vh;*/
  }
  table td{
    /*padding-top:2vh;*/
  }
  #ofix1_div_head th:nth-child(2){
    width: 3rem;
  }
  #ofix1_div_head th:nth-child(3){
    width: 4rem;
  }
  #tbTest1{
    width:23rem;
  }
  #tbTest1 td,#ofix1_tb_left td{
    height: 1.7rem;
  }
  #tbTest1 td:nth-child(1){
    /*box-shadow: #dddddd 2px 0px 0px;*/
  }
  #tbTest1 td:nth-child(3){
  }
  #tbTest1 th:nth-child(2){
    width: 3rem;
  }
  #tbTest1 th:nth-child(3){
    width: 4rem;
  }
  #tbheader td {
    background: #fff;
  }
  .under-line{
    text-decoration:underline;
  }
</style>
